package com.dfhz.ken.zermall.UI.activity.shopins;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dfhz.ken.zermall.R;
import com.dfhz.ken.zermall.UI.base.BaseActivity;
import com.dfhz.ken.zermall.utils.Base64Coder;

import java.io.ByteArrayOutputStream;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by huangyuekai on 16/11/24.
 */
public class FabuShopinActivity extends BaseActivity implements View.OnClickListener{
    @Bind(R.id.rel_title)
    RelativeLayout relTitle;
    @Bind(R.id.edt_describe)
    EditText edtDescribe;
    @Bind(R.id.img_ad1)
    ImageView imgAd1;
    @Bind(R.id.img_ad2)
    ImageView imgAd2;
    @Bind(R.id.img_ad3)
    ImageView imgAd3;
    @Bind(R.id.tvt_address)
    TextView tvtAddress;
    @Bind(R.id.rel_add_address)
    RelativeLayout relAddAddress;
    @Bind(R.id.rb_tejia)
    RadioButton rbTejia;
    @Bind(R.id.rb_dazhe)
    RadioButton rbDazhe;
    @Bind(R.id.rb_manjian)
    RadioButton rbManjian;
    @Bind(R.id.radio_group)
    RadioGroup radioGroup;
    @Bind(R.id.price_type_tejia)
    TextView priceTypeTejia;
    @Bind(R.id.price_type_dazhe)
    TextView priceTypeDazhe;
    @Bind(R.id.price_type_manjian)
    TextView priceTypeManjian;
    @Bind(R.id.edt_tejia_all_price)
    EditText edtTejiaAllPrice;
    @Bind(R.id.lin_tejia)
    LinearLayout linTejia;
    @Bind(R.id.edt_dazhe_zhekou)
    EditText edtDazheZhekou;
    @Bind(R.id.lin_dazhe)
    LinearLayout linDazhe;
    @Bind(R.id.edt_man_all)
    EditText edtManAll;
    @Bind(R.id.edt_man_jian)
    EditText edtManJian;
    @Bind(R.id.lin_manjian)
    LinearLayout linManjian;
    @Bind(R.id.tvt_start_time)
    TextView tvtStartTime;
    @Bind(R.id.tvt_end_time)
    TextView tvtEndTime;
    @Bind(R.id.tvt_leibie)
    TextView tvtLeibie;
    @Bind(R.id.lin_leibie)
    LinearLayout linLeibie;
    @Bind(R.id.tvt_pinpai)
    TextView tvtPinpai;
    @Bind(R.id.lin_pinpai)
    LinearLayout linPinpai;
    @Bind(R.id.btn_commit)
    TextView btnCommit;

    private static int TYPE_TEJIA = 0;
    private static int TYPE_DAZHE = 1;
    private static int TYPE_MANJIAN = 2;
    private int priceType = TYPE_DAZHE;

    private ImageView imageview;
    public static Uri photoUri;// 照相之后的数据
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    private String image1 = ""; // 存储图片字符串

    @Override
    protected void setMainLayout() {
        setContentView(R.layout.activity_shopin_fabu);
        ButterKnife.bind(this);
    }

    @Override
    protected void initBeforeData() {

    }

    @Override
    protected void initEvents() {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                setCheckUI();
                switch (checkedId){
                    case R.id.rb_tejia:
                        priceTypeTejia.setTextColor(getResources().getColor(R.color.red));
                        linTejia.setVisibility(View.VISIBLE);
                        priceType = TYPE_TEJIA;
                        break;
                    case R.id.rb_dazhe:
                        priceTypeDazhe.setTextColor(getResources().getColor(R.color.red));
                        linDazhe.setVisibility(View.VISIBLE);
                        priceType = TYPE_DAZHE;
                        break;
                    case R.id.rb_manjian:
                        priceTypeManjian.setTextColor(getResources().getColor(R.color.red));
                        linManjian.setVisibility(View.VISIBLE);
                        priceType = TYPE_MANJIAN;
                        break;
                }
            }
        });
        imgAd1.setOnClickListener(this);
    }

    @Override
    protected void initAfterData() {

    }

    @Override
    public void back(View view) {

    }

    private void setCheckUI(){
        linTejia.setVisibility(View.GONE);
        linDazhe.setVisibility(View.GONE);
        linManjian.setVisibility(View.GONE);
        priceTypeTejia.setTextColor(getResources().getColor(R.color.black));
        priceTypeDazhe.setTextColor(getResources().getColor(R.color.black));
        priceTypeManjian.setTextColor(getResources().getColor(R.color.black));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.img_ad1:
                new PopupWindows(FabuShopinActivity.this, imgAd1);
            break;
        }
    }

    private class PopupWindows extends PopupWindow {

        @SuppressWarnings("deprecation")
        public PopupWindows(Context mContext, View parent) {
            View view = View
                    .inflate(mContext, R.layout.item_popupwindows, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.pop_up_in));
            setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            setHeight(WindowManager.LayoutParams.MATCH_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();
            Button bt1 = (Button) view
                    .findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_cancel);
            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    takePhoto();
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    getPhoto();
                    dismiss();
                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });

        }
    }


    /**
     * 系统相机拍照
     *
     * @return
     */
    public void takePhoto() {
        // TODO Auto-generated method stub
        // 执行拍照前，应该先判断SD卡是否存在
        String SDState = Environment.getExternalStorageState();
        if (!SDState.equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "内存卡不存在", 1000).show();
            return;
        }
        try {
            photoUri = this.getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new ContentValues());
            if (photoUri != null) {
                Intent i = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                i.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(i, CAMERA_REQUEST_CODE);
                Log.e("takePhoto", "takePhoto");
            } else {
                Toast.makeText(this, "发生意外，无法写入相册", 1000).show();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            Toast.makeText(this, "发生异常，无法写入相册", 1000).show();
        }
    }


    /**
     * 从相册取照片
     */
    public void getPhoto() {
        Intent intentFromGallery = new Intent();
        intentFromGallery.setType("image/*"); // 设置文件类型
        //intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        intentFromGallery.setAction(Intent.ACTION_PICK);
        startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
    }


    /**
     * 回调函数处理
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // getActivity();
        // 结果码不等于取消时候
        if (resultCode != FragmentActivity.RESULT_CANCELED) {

            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    if (null != data) {
                        startPhotoZoom(data.getData());
                    }
                    break;
                case CAMERA_REQUEST_CODE:
                    Log.e("CAMERA_REQUEST_CODE", "CAMERA_REQUEST_CODE");
                    startPhotoZoom(photoUri);
                    break;
                case RESULT_REQUEST_CODE:
                    if (data != null) {
                        getImageToView(data);
                    }
                    break;
            }
        }
    }
    /**
     * 保存裁剪之后的图片数据
     *
     * @param data
     */
    @SuppressWarnings("deprecation")
    private void getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            imgAd1.setImageBitmap(photo);

            // 上传头像到服务器上去
            // bitmap 转换 String
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
            byte[] b = stream.toByteArray();
            // 将图片流以字符串形式存储下来
            image1 = new String(Base64Coder.encodeLines(b));
            // uploadImage(imageStrData);
        }
    }


    /**
     * 裁剪图片方法实现-
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Log.e("startPhotoZoom", "startPhotoZoom");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 350);
        intent.putExtra("outputY", 350);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }
}
